package com.example.chapter02;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.chapter02.util.DateUtil;
import com.example.chapter02.util.UsUtil;

import java.io.Serializable;

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String mRequest = "你睡了吗？来我家睡吧";
    private ActivityResultLauncher<Intent> register;
    private TextView tv_response;
    private EditText tv_name;
    private EditText tv_email;
    private EditText tv_number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_request);
        TextView tv_request = findViewById(R.id.tv_request);
        tv_request.setText("待发送的消息为：" + mRequest);

        tv_response = findViewById(R.id.tv_response);

        tv_name = findViewById(R.id.tv_name);
        tv_email = findViewById(R.id.tv_email);
        tv_number = findViewById(R.id.tv_number);

        findViewById(R.id.btn_request).setOnClickListener(this);

        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result != null) {
                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    Bundle bundle = intent.getExtras();
                    String response_time = bundle.getString("response_time");
                    String response_content = bundle.getString("response_content");
                    String desc = String.format("收到返回消息：\n应答时间为%s\n应答内容为%s\n",
                            response_time, response_content);
                    // 把返回消息的详情显示在文本视图上
                    tv_response.setText(desc);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, ActResponseActivity.class);
        UsUtil usUtil = new UsUtil(tv_name.getText().toString(), tv_number.getText().toString(), tv_email.getText().toString());

        // 创建一个新包裹
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DateUtil.getNowTime());
        bundle.putString("request_content", mRequest);
        bundle.putSerializable("student", usUtil);
        /*bundle.putString("response_name",usUtil.getName());
        bundle.putString("response_number",usUtil.getNumber());
        bundle.putString("response_email",usUtil.getEmail());*/

        intent.putExtras(bundle);
        register.launch(intent);
    }
}